package com.woniu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.Goods;
import com.alipay.api.domain.OrderGoodsDTO;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.exception.userexp.YogaException;
import com.woniu.order.Param.ApplyParam;
import com.woniu.order.client.ProductClient;
import com.woniu.order.dao.GoodsItemDao;
import com.woniu.order.dao.GoodsOrderDao;
import com.woniu.order.dto.RefundDto;
import com.woniu.order.model.GoodsItem;
import com.woniu.order.model.GoodsOrder;
import com.woniu.order.model.Refund;
import com.woniu.order.dao.RefundDao;
import com.woniu.order.service.RefundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.woniu.order.client.GoodsDto;
import com.woniu.util.StateUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月12日
 */
@Service
public class RefundServiceImpl extends ServiceImpl<RefundDao, Refund> implements RefundService {

    @Resource
    private GoodsOrderDao goodsOrderMapper;
    @Resource
    private  RefundDao refundMapper;
    @Resource
    private GoodsItemDao goodsItemMapper;
    @Resource
    private ProductClient productClient;

    @Resource
    private AlipayClient alipayClient;


    @Override
    public void apply(ApplyParam param) {
        GoodsOrder goodsOrder = goodsOrderMapper.selectById(param.getOrderNum());
        if(goodsOrder.getOrderState()== StateUtil.ORDER_STATE_NOT_EVALUATE){
            throw new YogaException(6001,"已退款，请勿重复提交");
        }
        Refund refund = BeanUtil.toBean(param, Refund.class);
        refund.setRefundState(2);
        refundMapper.insert(refund);
        goodsOrder.setOrderState(StateUtil.ORDER_STATE_NOT_EVALUATE);
        goodsOrderMapper.updateById(goodsOrder);
    }

    @Override
    public List<RefundDto> loadAllRefund(Integer refundState) {
        QueryWrapper<Refund> wrapper=new<Refund>QueryWrapper();
        if (refundState != null){
            if (refundState.equals(0)){
                wrapper.ne("refund_state",2);
            }else {
                wrapper.eq("refund_state",2);
            }
        }
        List<Refund> list = refundMapper.selectList(wrapper);

        ArrayList<RefundDto> refundDtos = new ArrayList<>();
        for (Refund r:list
        ) {
            RefundDto refundDto = BeanUtil.toBean(r, RefundDto.class);
            refundDtos.add(refundDto);


        }

        return refundDtos;
    }

    @Override
    public List<Refund> selctRefund() {
        QueryWrapper<Refund> wrapper = new QueryWrapper<>();
        List<Refund> list = refundMapper.selectList(wrapper);
        return list;
    }

    @Override
    public void sendRefundQueue(String orderNum) throws AlipayApiException {
        QueryWrapper<Refund> wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",orderNum);
        Refund refund = refundMapper.selectOne(wrapper);
        if (refund.getRefundState()!=2){
            throw new YogaException(8400,"不能重复提交");
        }

        refund(orderNum);
    }

    public void refund(String orderNum) throws AlipayApiException {
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        QueryWrapper<Refund> wrapper=new QueryWrapper<Refund>();
        wrapper.eq("order_num",orderNum);
        Refund refund = refundMapper.selectOne(wrapper);
        String out_trade_no = orderNum;
        String refund_reason= refund.getRefundReason();
        String out_request_no=new Snowflake(1,1).nextIdStr();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");
        String result = alipayClient.execute(alipayRequest).getBody();
        String response = JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString();
        String code=JSONUtil.parseObj(response).get("code").toString();
        if(code.equals("10000")){
            String status = JSONUtil.parseObj(response).get("msg").toString();
            if("Success".equals(status)){
                agreeRefund(orderNum);
            }
        }
    }
    public  void agreeRefund(String orderNum) {
        GoodsOrder goodsOrder = goodsOrderMapper.selectById(orderNum);
        if(goodsOrder.getOrderState()==StateUtil.GOODS_ORDER_STATE_COMPLETE){
            throw new YogaException(6661,"不能重复退款");
        }
        if(goodsOrder.getOrderState()==StateUtil.GOODS_ORDER_STATE_REFOUNDING){
            goodsOrder.setOrderState(StateUtil.GOODS_ORDER_STATE_COMPLETE);
            List<GoodsItem> list=goodsItemMapper.selectList(new QueryWrapper<GoodsItem>().eq("order_num",orderNum));
            for (GoodsItem item : list) {
                GoodsDto data = productClient.byId(item.getGoodsId()).getData();
                GoodsDto goodsDto = new GoodsDto();
                goodsDto.setGoodsNum(item.getGoodsNum());
                goodsDto.setGoodsNum(goodsDto.getGoodsNum()+item.getGoodsNum());
                productClient.updateByIdGoods(BeanUtil.toBean(goodsDto, Goods.class));
            }
            goodsOrderMapper.updateById(goodsOrder);
            QueryWrapper<Refund>wrapper=new QueryWrapper<Refund>();
            wrapper.eq("order_num",orderNum);
            Refund refund = refundMapper.selectOne(wrapper);
            if(refund.getRefundState()==0){
                refund.setRefundState(1);
                refundMapper.updateById(refund);
            }
        }

    }

    @Override
    public void rejectRefund(Integer refundId) {
        Refund refund = baseMapper.selectById(refundId);
        if (refund == null){
            throw new YogaException(3303,"无此退款申请");
        }
        if (!refund.getRefundState().equals(2)){
            throw new YogaException(3304,"该退款申请状态异常");
        }
        refund.setRefundState(0);
        baseMapper.updateById(refund);
    }
}
